package com.ncmmall.api.exception;


import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author linxs
 *         异常拦截器
 */
@Controller
@Component
@RequestMapping("/error")
public class ExceptionApi implements ErrorController {
    private static final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

    @Override
    public String getErrorPath() {
        return PATH;
    }


    @RequestMapping
    @ResponseBody
    public JSONObject doHandleError(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> errorAttributesData = errorAttributes.getErrorAttributes(requestAttributes, true);
        Integer status = (Integer) errorAttributesData.get("status");
        String messageFound = (String) errorAttributesData.get("message");

        JSONObject data = new JSONObject();
        data.put("result", -1);
        data.put("data", new JSONObject());
        data.put("msg", "[状态码：" + status + "]" + messageFound);
        return data;
    }
}
